package com.xyy.saas.payment.callback.core.job;

import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import com.xyy.elasticjob.client.annotation.ElasticJobConf;
import com.xyy.saas.payment.adpater.RouteManager;
import com.xyy.saas.payment.callback.core.result.CallbackRunner;
import com.xyy.saas.payment.common.Constants;
import com.xyy.saas.payment.common.RocketMqTopic;
import com.xyy.saas.payment.cores.bo.QueryResultBo;
import com.xyy.saas.payment.dao.mapper.WithdrawOrderMapper;
import com.xyy.saas.payment.dao.model.PayAccount;
import com.xyy.saas.payment.dao.model.WithdrawOrder;
import com.xyy.saas.payment.merchant.core.dto.QueryTradeStatusDto;
import com.xyy.saas.payment.merchant.core.dto.QueryTradeStatusVo;
import com.xyy.saas.payment.service.PayAccountService;
import com.xyy.saas.payment.util.JSONUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 同步提现状态
 */
@Slf4j
@ElasticJobConf(name = "com.xyy.saas.payment.callback.core.job.SyncWithdrawStatusJob", cron = "0 0/1 * * * ? ")
public class SyncWithdrawStatusJob implements SimpleJob {
    @Resource
    private WithdrawOrderMapper withdrawOrderMapper;
    @Resource
    private RouteManager routeManager;
    @Resource
    private PayAccountService payAccountService;
    @Resource
    private CallbackRunner callbackRunner;

    @Override
    public void execute(ShardingContext shardingContext) {
        log.info("SyncWithdrawStatusJob#execute start.");

        int pageOffset = 0;
        int pageSize = 50;

        while(true) {
            List<WithdrawOrder> items = withdrawOrderMapper.
                    selectListByStatusAndPayChannel(Constants.PINGAN, WithdrawOrder.STATUS_IN, pageOffset, pageSize);

            if(CollectionUtils.isEmpty(items)) {
                return;
            }

            for(WithdrawOrder item : items) {
                try {
                    PayAccount payAccount = payAccountService.getPayAccountByAccountId(item.getUserId());

                    QueryTradeStatusDto queryTradeStatusDto = QueryTradeStatusDto.builder().
                            businessIdType(payAccount.getBusinessIdType()).
                            accountId(item.getUserId()).
                            tradeType(QueryTradeStatusDto.WITHDRAW).
                            tradeNo(item.getWithdrawNo()).
                            tradeDate(item.getCreateTime()).
                            build();
                    QueryTradeStatusVo queryTradeStatusVo = routeManager.queryTradeStatus(queryTradeStatusDto);

                    switch(queryTradeStatusVo.getStatus()) {
                        case QueryResultBo.PROCESSING:
                            break;
                        case QueryResultBo.FINISHED:
                        case QueryResultBo.FAILED:
                            // 1.组装参数
                            Map<String, String> noticeParam = new HashMap<>();
                            noticeParam.put("status", queryTradeStatusVo.getStatus());
                            noticeParam.put("withdrawNo", item.getWithdrawNo());
                            noticeParam.put("errorMsg", queryTradeStatusVo.getErrorMsg());

                            // 2.发送通知
                            callbackRunner.syncSendMsg(RocketMqTopic.TOPIC_WITHDRAW_NOTICE, noticeParam);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported Operation withdraw status." +
                                    "queryTradeStatusDto=" + JSONUtils.toJSON(queryTradeStatusDto));
                    }
                }
                catch(Exception ex)  {
                    log.error(ex.getMessage() + "，withdrawOrderw=" + JSONUtils.toJSON(item), ex);
                }
            }
        }
    }
}
